package com.hmjk.health.user;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.hmjk.health.HealthApp;
import com.hmjk.health.R;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.background.NetService;
import com.hmjk.health.card.InterestDeviceDialog;
import com.hmjk.health.card.InterestDeviceDialog.OnInterestDialogDismissListener;
import com.hmjk.health.home.DeviceManagerActivity;
import com.hmjk.health.home.HomeActivity;
import com.hmjk.health.util.DEV_DATA;
import com.hmjk.health.util.TODO_DATA;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

public class ToDoActivity extends Activity implements OnClickListener{
	private final String TAG = ToDoActivity.class.getSimpleName();
	private HealthApp mApp = null;
	private TextView mWho;
	private TextView mWhat;
	private TextView mTime;
	private TODO_DATA mData;
	private String username;
	private String familyname;
	private String devname;
	private String extraMsg;
	
	private void logd(String info){
		Log.d(TAG,info);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		logd("onCreate");
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mApp = (HealthApp)getApplication();
		
		Intent i = getIntent();
		mData = (TODO_DATA) i.getSerializableExtra("data");
		//String info = i.getStringExtra("info");
		
		setContentView(R.layout.todo_activity);
		ImageButton back = (ImageButton)findViewById(R.id.back);
		back.setOnClickListener(this);
		
		mWho = (TextView) findViewById(R.id.todo_who);
		mWhat = (TextView) findViewById(R.id.todo_what);
		mTime = (TextView) findViewById(R.id.todo_time);
		
		parseActors(mData);
		String who = getWhoString(mData);
		if(who != null){
			mWho.setText(who);
		}else{
			mWho.setVisibility(View.GONE);
		}
		String what = getWhatString(mData);
		
		mWhat.setText(what);
		
		Time time = new Time();
		time.setToNow();
		
		time.set(mData.time);
		
		String timestr = String.format("%04d-%02d-%02d %02d:%02d", time.year,time.month+1,
				time.monthDay, time.hour, time.minute);
		
		if(mData.code.equals("0401") || mData.code.equals("0402") || mData.code.equals("0404")){
			mTime.setText(getResources().getString(R.string.todo_happend_time, timestr));
		}else if(mData.code.equals("0601")){
			mTime.setText(timestr);
		}else{
			mTime.setText(getResources().getString(R.string.todo_apply_time, timestr));
		}
		Button agree = (Button) findViewById(R.id.agree);
		Button deny = (Button) findViewById(R.id.deny);
		Button check = (Button) findViewById(R.id.check);
		
		agree.setOnClickListener(this);
		deny.setOnClickListener(this);
		check.setOnClickListener(this);
		
		agree.setText(R.string.todo_agree);
		deny.setText(R.string.todo_deny);
		
		check.setVisibility(View.GONE);
		if(mData.code.equals("0404")){
			agree.setVisibility(View.GONE);
			deny.setVisibility(View.GONE);
		}else if(mData.code.equals("0401") || mData.code.equals("0402")){
			agree.setVisibility(View.GONE);
			deny.setVisibility(View.GONE);
			check.setVisibility(View.VISIBLE);
		}else if(mData.code.equals("0601")){
			agree.setText(R.string.todo_accept);
			deny.setText(R.string.todo_ignore);
		}
	}
	
	private String getWhoString(TODO_DATA d){
		if(d.code.equals("0201") || d.code.equals("0301")){
			return username;
		}else if(d.code.equals("0601")){
			return null;
		}else{
			return devname;
		}
	}
	
	private String getWhatString(TODO_DATA d){
		if(d.code.equals("0201")){
			String info = getResources().getString(R.string.apply_family, familyname);
			return info;
		}else if(d.code.equals("0301")){
			String info = getResources().getString(R.string.apply_device, devname);
			return info;
		}else if(d.code.equals("0401")){
			String info = getResources().getString(R.string.apply_over_fence);
			return info;
		}else if(d.code.equals("0402")){
			String info = getResources().getString(R.string.apply_low_power);
			return info;
		}else if(d.code.equals("0403")){
			String info = getResources().getString(R.string.apply_dev_simchange);
			return info;
		}else if(d.code.equals("0404")){
			String info = getResources().getString(R.string.apply_dev_frozen);
			return info;
		}else if(d.code.equals("0601")){	
			String info = getResources().getString(R.string.apply_invitation_by_dev, extraMsg);
			return info;
		}
		return "";
	}
	
	private void parseActors(TODO_DATA d){
		if(d.code.equals("0201")){
			String[] fargs = new String[1];
			fargs[0] = d.fid;
			JSONObject fajson = (JSONObject) mApp.getDataManager().checkData(DataManager.F_FAMILYLIST, fargs);
			if(fajson != null){
				try {
					familyname = fajson.getString("name");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					familyname = null;
				}
			}
			
			if(familyname == null){
				familyname = getResources().getString(R.string.noFaName);
			}else if(familyname.length() > 10){
				familyname = familyname.substring(0, 10)+"...";
			}
			
			try {
			if(d.mark != null){
				JSONObject mark = new JSONObject(d.mark);
				if(mark.has("nickname")){
					username = mark.getString("nickname");
				}
				if((username == null) || (username.trim().length() == 0)){
					if(mark.has("username")){
						username = mark.getString("username");
					}
				}
			}
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			if((username == null) || (username.trim().length() == 0)){
				username = getResources().getString(R.string.noName);
			}
		}else if(d.code.equals("0601")){
			extraMsg = getResources().getString(R.string.none);
			try {
				if(d.mark != null){
					JSONObject mark = new JSONObject(d.mark);
					if(mark.has("username")){
						extraMsg = mark.getString("username");
					}
				}
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}else{
			String[] args = new String[2];
			args[0] = "DEV_TID";
			args[1] = d.tid;
			JSONObject devjson = (JSONObject) mApp.getDataManager().checkData(DataManager.F_DEVICELIST, args);
			if(devjson != null){
				try{
					JSONArray ar = devjson.getJSONArray("array");
					if(ar.length() > 0){
						JSONObject e = ar.getJSONObject(0);
						String tid = e.getString("tid");
						if(tid.equals(d.tid)){
							devname = e.getString("name");
						}
					}
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			if(devname == null){
				devname = getResources().getString(R.string.noName);
			}
			
			if(d.code.equals("0301")){
				/*
				String[] uargs = new String[1];
				uargs[0] = d.uid;
				JSONObject ujson = (JSONObject) mApp.getDataManager().checkData(DataManager.F_FAMILYMEMBER, uargs);
			
				if(ujson != null){
					try {
						username = ujson.getString("name");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						username = null;
					}
				}
				*/
				
				try {
					if(d.mark != null){
						JSONObject mark = new JSONObject(d.mark);
						if(mark.has("nickname")){
							username = mark.getString("nickname");
						}
						if((username == null) || (username.trim().length() == 0)){
							if(mark.has("username")){
								username = mark.getString("username");
							}
						}
					}
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				if(username == null){
					username = getResources().getString(R.string.noFaName);
				}
			}
		}
	}
	
	private void response(){
		mApp.showWaitting(this, null);
		mApp.getDataManager().commitData(DataManager.F_TODO, mData);
	}
	
	private BroadcastReceiver mReceiver = new BroadcastReceiver(){
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action.equals(DataManager.DATA_COMMIT_RESULT)){
				String type = intent.getStringExtra("type");
				if(type.equals(DataManager.F_TODO)){
					mApp.dismissWaiting();
					String state = intent.getStringExtra("state");
					int code = intent.getIntExtra("code", 400);
					if(code != 200){
						mApp.showAlertDialog(ToDoActivity.this, R.string.commit_err);
					}else if(state.equals("00") == false){
						mApp.showAlertDialog(ToDoActivity.this, R.string.commit_err);
					}else{
						if(mData.code.equals("0601") && mData.agree == true)
						{
							mApp.getDataManager().setUserData(DataManager.F_DEVICELIST, null);
							mApp.getDataManager().refreshData(DataManager.F_DEVICELIST);
						}
						Intent i = new Intent("Dealed");
						ToDoActivity.this.setResult(RESULT_OK, i);
						finish();
					}
				}else if(type.equals(DataManager.F_DEVICELIST)){
					String state = intent.getStringExtra("state");
					int code = intent.getIntExtra("code", 400);
					String cmd = intent.getStringExtra("cmd");
					if(cmd.equals("COMMIT_DEVICE_ADMIN_APPLY")){
						if(code != 200){
							mApp.dismissWaiting();
							mApp.showAlertDialog(ToDoActivity.this, R.string.commit_err);
						}else if(state.equals("00") == false){
							mApp.dismissWaiting();
							mApp.showAlertDialog(ToDoActivity.this, R.string.commit_err);
						}else{
							mApp.dismissWaiting();
							response();
						}
					}
					
				}
			}
			
		}
	};
	
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			switch(msg.what){
			case HealthApp.MSG_NET_RESPONSE:{
				Bundle b = msg.getData();
				String stamp = b.getString("stamp","ooh!No!");
				boolean canceled = b.getBoolean("canceled", false);
				if(stamp.startsWith("APPLY_INTEREST_DEV_0601")){
					String sjson = b.getString("json");
					if(sjson != null){
						try {
							JSONObject json = new JSONObject(sjson);
							int code = json.getInt("code");
							JSONObject sd = json.getJSONObject("senddata");
							String tid = sd.getString("tid");
							String inputname = sd.getString("devicename");
							if(code == 200){
								String state = json.getString("state");
								if(state.equals("00")){
									mApp.dismissWaiting();
									String txt = getResources().getString(R.string.applydev_ok);
									mApp.showAlertDialog(ToDoActivity.this, txt, R.string.Yes, null);
									response();
									return;
								}else if(state.equals("27")){
									if(false == applyAdmin(tid,inputname)){
										mApp.dismissWaiting();
										mApp.showAlertDialog(ToDoActivity.this, R.string.apply_failed);
									}
									return;
								}
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						mApp.dismissWaiting();
						mApp.showAlertDialog(ToDoActivity.this, R.string.apply_failed);
					}
				}
			}
			break;
			}
		}
	};
	
	@Override
	public void onPause(){
		super.onPause();
		unregisterReceiver(mReceiver);
		mApp.dismissWaiting();
		finish();
	}
	
	@Override
	public void onResume(){
		super.onResume();
		IntentFilter filter = new IntentFilter();
		filter.addAction(DataManager.DATA_COMMIT_RESULT);
		registerReceiver(mReceiver, filter);
	}
	
	private boolean applyInterest(String tid){
		if((tid == null) || tid.trim().isEmpty())
			return false;
		
		InterestDeviceDialog.open(this, tid, "", new OnInterestDialogDismissListener(){

			@Override
			public void onDismiss(boolean toBeApply, DEV_DATA data) {
				if(toBeApply && (data != null)){
					mApp.showWaitting(ToDoActivity.this, null);
					
					Intent si = new Intent(ToDoActivity.this, NetService.class);
					si.setAction(NetService.APPLY_INTEREST_DEV);
					si.putExtra("uid", mApp.getUID());
					si.putExtra("interestuid", mApp.getUID());
					si.putExtra("tid", data.id);
					si.putExtra("did", "");
					si.putExtra("devicename", data.name);
					
					Time t = new Time();
					t.setToNow();
					String stamp = "APPLY_INTEREST_DEV_0601" + t.toString(); 
					si.putExtra("stamp",stamp);
					mApp.addNetHandler(stamp,mHandler);
					startService(si);
				}
			}
		});
		return true;
	}
	
	private boolean applyAdmin(String tid, String name){
		boolean ok = false;
		try {
			JSONObject commit = new JSONObject();
			
			commit.put("cmd", "bindadmin");
			commit.put("tid", tid);
			commit.put("devicename", name);
			
			ok = mApp.getDataManager().commitData(DataManager.F_DEVICELIST, commit);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ok;
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.back:{
			finish();
		}break;
		case R.id.agree:{
			mData.agree = true;
			if(mData.code.equals("0601")){
				if(false == applyInterest(mData.tid)){
					mApp.showAlertDialog(ToDoActivity.this, R.string.commit_err);
				}
			}else{
				response();
			}
		}break;
		case R.id.deny:{
			mData.agree = false;
			response();
		}break;
		case R.id.check:{
			Intent i = new Intent("CheckDevice");
			i.putExtra("tid", mData.tid);
			i.putExtra("code", mData.code);
			setResult(RESULT_OK, i);
			finish();
		}break;
		}
	}
}
